<template>
	<view @touchstart="touchStart" @touchend="touchEnd">
		<u-navbar :is-back="true" title="答题"></u-navbar>
		<view style="display: flex;align-items: center;padding-left: 10px">
			<u-icon size="50" name="https://xyh.zjit.ac.cn/profile/upload/2024/12/06/time.png"></u-icon>
			<u-count-down ref="countDown" autoplay :show-days="false" separator="colon" separator-size="30" font-size="30" />
		</view>
		<view style="text-align: right;width: 98%;padding: 5px;display: flex;justify-content: space-between">
			<view>
				<text class="u-type-info" style="font-size: 18px">{{ index + 1 }}</text>
				/{{ questionList.length }}
			</view>
		</view>
		<u-line-progress height="10" :show-percent="false" active-color="#09AFFF" :percent="(index + 1) / questionList.length * 100"></u-line-progress>
		<u-card>
		    <view slot="body" class="content-container">
		        <view>
		            <u-tag shape="square" type="info" text="单选题"></u-tag>
		        </view>
		        <view style="margin-top: 10px; padding-left: 5px; padding-bottom: 5px">
		            <u-parse :html="question.content" style="font-size: 13px;" :selectable="true" :lazy-load="true"></u-parse>
		        </view>
		        <view style="padding-left: 5px; padding-top: 8px">
		            <u-radio-group @change="handleChange" wrap v-model="userAnswer" :disabled="isSubmitted" :size="70">
		                <u-radio style="margin-top: 20px" v-for="(item, index) in options" :key="index"
		                    :name="item.name.toUpperCase()">
		                    <view style="width: 100%; display: flex">
		                        <u-parse :html="item.text" style="font-size: 13px;" :selectable="true" :lazy-load="true"></u-parse>
		                    </view>
		                </u-radio>
		            </u-radio-group>
		        </view>
		
		        <!-- 答案对比 -->
		        <view v-if="isSubmitted" class="answer-card rounded-card" style="margin-top: 10px;">
		            <view class="card-content">
		                <text :style="{ color: userAnswer === question.answer.toUpperCase() ? '#32CD32' : '#FF0000' }">
		                    我的答案: {{ userAnswer || '未选择' }}
		                </text>
		                <span style="margin-left: 10px;"></span> <!-- 水平间距 -->
		                <text>正确答案: {{ question.answer.toUpperCase() }}</text>
		            </view>
		        </view>
		
		        <!-- 题目解析 -->
		        <view v-if="isSubmitted" class="explanation-card rounded-card" style="margin-top: 10px;">
		            <view class="card-content">
		                <text>题目解析:</text>
		                <u-parse :html="question.explanation"></u-parse>
		            </view>
		        </view>
		    </view>
		</u-card>
		<view class="space"></view>
		<view style="position: fixed; bottom: 0px; width: 750rpx; display: flex; border-top: 1px solid #ccc; padding-top: 8px; padding-bottom: 5px; background-color: white; z-index: 1019;">
			<view style="width: 500rpx">
				<u-row gutter="16" style="font-size: 26rpx;color: #000000">
					<u-col text-align="center" span="4">
						<view @click="toggleFavorite">
							<u-icon size="50"
								name="https://xyh.zjit.ac.cn/profile/upload/2024/12/06/collect.png"></u-icon>
						</view>
						<view style="font-weight: bold">收藏</view>
					</u-col>
					<u-col text-align="center" span="4">
						<view @click="showCard=true">
							<u-icon size="50"
								name="https://xyh.zjit.ac.cn/profile/upload/2024/12/06/datika.png"></u-icon>
						</view>
						<view style="font-weight: bold">答题卡</view>
					</u-col>
					<u-col text-align="center" span="4">
						<view>
							<u-icon size="50"
								name="https://xyh.zjit.ac.cn/profile/upload/2024/12/06/cuotifankui.png"></u-icon>
						</view>
						<view style="font-weight: bold">错误反馈</view>
					</u-col>
				</u-row>
			</view>
			<view style="display: flex; align-items: center; justify-content: center; font-weight: bold;">
				<u-button shape="square" :custom-style="{height:'33px', width:'223rpx'}" @click="next"
					:disabled="isSubmitted">
					{{ index === questionList.length - 1 ? '交卷' : '下一题' }}
				</u-button>
			</view>
		</view>

		<u-popup v-model="showCard" mode="bottom" height="600" border-radius="14">
			<view style="padding: 5px;width: 100%;display: flex;flex-wrap: wrap;justify-content: left">
				<button :style="{
				        backgroundColor: !isSubmitted 
				            ? (ob.userAnswer ? '#09AFFF' : '#add8e6')
				            : (ob.userAnswer === null ? '#fab6b6' : (ob.userAnswer.toUpperCase() === ob.answer.toUpperCase() ? '#09AFFF' : '#FF0000'))
				    }" @click="switchQuestion(index)" v-for="(ob, index) in answers" class="circle-button">
					{{ index + 1 }}
				</button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import UNavbar from "@/uview-ui/components/u-navbar/u-navbar.vue";
	import UCard from "@/uview-ui/components/u-card/u-card.vue";
	import ULoadingPage from "@/uview-ui/components/u-loading-page/u-loading-page.vue";
	import UTag from "@/uview-ui/components/u-tag/u-tag.vue";
	import UButton from "@/uview-ui/components/u-button/u-button.vue";
	import UIcon from "@/uview-ui/components/u-icon/u-icon.vue";
	import URadio from "@/uview-ui/components/u-radio/u-radio.vue"
	import URadioGroup from "@/uview-ui/components/u-radio-group/u-radio-group.vue"
	import {
		toast
	} from "@/utils/common";
	import {
		allQuestions,
		allQuestionss
	} from "@/api/business/question";
	import {
		addUserquestions,
		allUserquestionss,
		updateUserquestions
	} from "@/api/business/userquestions";
	import {
		getUserProfile
	} from "@/api/system/user";
	import {
		getPaper
	} from "@/api/business/paper";

	export default {
		components: {
			URadio,
			URadioGroup,
			UIcon,
			UButton,
			UTag,
			ULoadingPage,
			UCard,
			UNavbar
		},
		data() {
			return {
				isLocked: false,
				showCard: false,
				isSubmitted: false,
				index: 0,
				questionList: [],
				question: {},
				answers: [],
				userAnswer: '',
				options: [],
				userId: null, // 用户ID
				questionType: null, // 题目类型
				startTime: null,
				startX: 0, // 触摸开始的X坐标
				timerRunning: true, // 添加一个标志来控制计时器
				paperId: null
			};
		},
		onLoad(e) {
			const { type, count, paperId, questionIds } = e;

			this.getUserId();

			if (questionIds) {
				// 解析传递的题目ID列表
				const ids = JSON.parse(questionIds);
				this.loadQuestionsByIds(ids);
			} else if (paperId) {
				this.paperId = paperId;
				this.loadQuestionsByPaperId(paperId);
			} else {
				const questionCount = parseInt(count) || 3;
				this.loadQuestionsByType(type, questionCount);
			}
		},

		watch: {
			index(newValue) {
				this.question = this.questionList[newValue];
				this.initializeOptions();
				const firstMatch = this.answers.find(item => item.questionId === this.question.id);
				this.userAnswer = firstMatch ? firstMatch.userAnswer : '';
				this.questionType = this.question.type;
			},
		},
		methods: {
			loadQuestionsByIds(ids) {
				allQuestionss({
					ids: JSON.stringify(ids)
				}).then(re => {
					this.questionList = re.data.sort(() => 0.5 - Math.random()); // 打乱顺序
					this.index = 0;
					this.question = this.questionList[this.index];
					this.initializeOptions();
					this.initializeAnswers();
					this.startTime = Date.now();
				}).catch(error => {
					console.error("获取题目数据失败", error);
				});
			},
			loadQuestionsByType(type, count) {
			    allQuestions({
			        type: type
			    }).then(re => {
			        this.questionList = this.getRandomQuestions(re.data, count);
			        this.index = 0;
			        this.question = this.questionList[this.index];
			        this.questionType = this.question.type; // 立即设置题目类型
			        this.initializeOptions();
			        this.initializeAnswers();
			        this.startTime = Date.now(); // 记录开始时间
			    });
			},
			loadQuestionsByPaperId(paperId) {
			    allQuestions({ paperid: paperId }).then(re => {
			        this.questionList = re.data.sort((a, b) => a.idInPaper - b.idInPaper);
			        this.index = 0;
			        this.question = this.questionList[this.index];
					this.questionType = this.question.type; // 立即设置题目类型
			        this.initializeOptions();
			        this.initializeAnswers();
			        this.startTime = Date.now(); // 记录开始时间
			    }).catch(error => {
			        console.error("获取题目数据失败", error);
			    });
			},
			initializeOptions() {
				this.options = [];
				this.options.push({
					name: 'a',
					text: this.question.a
				});
				this.options.push({
					name: 'b',
					text: this.question.b
				});
				this.options.push({
					name: 'c',
					text: this.question.c
				});
				this.options.push({
					name: 'd',
					text: this.question.d
				});
			},
			initializeAnswers() {
				this.answers = [];
				for (let ob of this.questionList) {
					this.answers.push({
						questionId: ob.id,
						answer: ob.answer,
						userAnswer: null
					});
				}
				const firstMatch = this.answers.find(item => item.questionId === this.question.id);
				this.userAnswer = firstMatch ? firstMatch.userAnswer : '';
			},
			getRandomQuestions(questions, count) {
				const shuffled = questions.sort(() => 0.5 - Math.random());
				return shuffled.slice(0, count);
			},
			handleChange() {
				this.updateUserAnswer(this.question.id, this.userAnswer);
			},
			switchQuestion(e) {
				this.index = e;
			},
			getUserId() {
				getUserProfile().then(response => {
					this.userId = response.data.userId;
				}).catch(error => {
					console.error("获取用户信息失败", error);
				});
			},
			toggleFavorite() {
			    const currentQuestionId = this.question.id;
				// 查询用户是否已经收藏该题目
			    allUserquestionss({ userId: this.userId, questionId: currentQuestionId }).then(response => {
			        if (response && response.data) {
			            if (Array.isArray(response.data)) {
			                const existingRecord = response.data.find(item => item.userId == this.userId && item.questionId == currentQuestionId);
			                if (!existingRecord) {
			                    // 新增数据
			                    const dataToSave = {
			                        userId: this.userId,
			                        questionId: currentQuestionId,
			                        status: null, // 默认值
			                        type: this.questionType,
			                        star: 0 // 表示已收藏
			                    };
			                    addUserquestions(dataToSave).then(() => {
			                        uni.showToast({
			                            title: '收藏成功',
			                            icon: 'success'
			                        });
			                    });
			                } else {
			                    // 更新 star 值
			                    const newStar = existingRecord.star === 0 ? 1 : 0; // 取反
			                    const newStatus = existingRecord.status === 1 ? 1 : existingRecord.status; // 如果status为1则保持不变
			                    updateUserquestions({
			                        userId: this.userId,
			                        questionId: currentQuestionId,
			                        star: newStar, // 更新 star
			                        status: newStatus, // 更新 status
			                        id: existingRecord.id // 使用记录的 ID 进行更新
			                    }).then(() => {
			                        uni.showToast({
			                            title: newStar === 0 ? '已收藏' : '已取消收藏',
			                            icon: 'success'
			                        });
			                    }).catch(error => {
			                        console.error("更新收藏失败", error);
			                        uni.showToast({
			                            title: '收藏失败, 请稍后再试',
			                            icon: 'none'
			                        });
			                    });
			                }
			            } else {
			                console.error("查询收藏失败: response.data 不是一个有效的数组", response.data);
			                uni.showToast({
			                    title: '收藏失败, 请稍后再试',
			                    icon: 'none'
			                });
			            }
			        } else {
			            console.error("查询收藏失败: 响应格式不正确", response);
			            uni.showToast({
			                title: '收藏失败, 请稍后再试',
			                icon: 'none'
			            });
			        }
			    }).catch(error => {
			        console.error("查询收藏失败", error);
			        uni.showToast({
			            title: '收藏失败, 请稍后再试',
			            icon: 'none'
			        });
			    });
			},
			submit() {
				this.$refs.countDown.clearTimer(); // 停止 u-count-down 计时
			    this.isSubmitted = true;
			    this.timerRunning = false;
			    const endTime = Date.now();
			    const timeTaken = Math.floor((endTime - this.startTime) / 1000);
			    let correctCount = 0;
			    const promises = []; // 用于存储所有的Promise
			    const questionIds = this.questionList.map(q => q.id); // 所有题目的 ID
			    const wrongIds = [];
			
			    // 如果有 paperId，说明是刷卷子模式，跳过题目的记录逻辑
			    if (this.paperId) {
			        // 只记录卷子相关的信息，不记录题目
			        this.answers.forEach(answer => {
			            const userAnswer = answer.userAnswer ? answer.userAnswer.toUpperCase() : '';
			            const correctAnswer = answer.answer.toUpperCase();
			            const status = userAnswer == answer.answer.toUpperCase() ? 0 : 1; // 如果做对则status为0
			            correctCount += userAnswer == answer.answer.toUpperCase() ? 1 : 0;
			            if (status === 1) {
								wrongIds.push(answer.questionId);
			            }
			        });
			
			        // 这里处理卷子的记录逻辑
			        allUserquestionss({ userId: this.userId, paperId: this.paperId }).then(response => {
			            if (!response.data.length) {
			                const paperData = {
			                    userId: this.userId,
			                    status: null,
			                    paperId: this.paperId,
			                    questionId: null,
			                    type: null,
			                    star: null
			                };
			
			                // 插入到 userquestions 表
			                return addUserquestions(paperData).then(() => {
			                });
			            }
			        }).catch(error => {
			            console.error("查询试卷记录失败", error);
			        });
			
			        // 获取试卷名称并导航到报告页面
			        getPaper(this.paperId).then(response => {
			            const practiceType = response.data.name;
			            this.navigateToReport(practiceType, endTime, timeTaken, ((correctCount / questionIds.length) * 100).toFixed(2), questionIds, wrongIds);
			        }).catch(error => {
			            console.error("获取试卷名称失败", error);
			        });
			
			        return;
			    }
			
			    // 如果不是刷卷子模式，则记录题目答案
			    this.answers.forEach(answer => {
			        const userAnswer = answer.userAnswer === undefined ? '' : answer.userAnswer;
			        const status = userAnswer === answer.answer.toUpperCase() ? 0 : 1; // 如果做对则status为0
			        const star = 1; // 默认未收藏
			
			        if (userAnswer !== '') { // 只记录已作答的题目
			            const dataToSave = {
			                userId: this.userId,
			                questionId: answer.questionId,
			                type: this.questionType,
			                status: status,
			                star: star
			            };
			
			            // 检查是否已有记录
			            promises.push(allUserquestionss({ userId: this.userId, questionId: answer.questionId }).then(response => {
			                if (!response.data.length) {
			                    // 新增记录
			                    return addUserquestions(dataToSave);
			                } else {
			                    // 更新记录
			                    const existingRecord = response.data[0];
			                    const newStatus = existingRecord.status === 1 ? 1 : status; // 如果status为1则保持不变
			                    return updateUserquestions({
			                        userId: this.userId,
			                        questionId: answer.questionId,
			                        status: newStatus,
			                        star: existingRecord.star, // 保持原有的收藏状态
			                        id: existingRecord.id // 使用记录的 ID 进行更新
			                    });
			                }
			            }));
			
			            if (userAnswer === answer.answer.toUpperCase()) {
			                correctCount++;
			            } else {
			                wrongIds.push(answer.questionId);
			            }
			        }
			    });
			
			    // 等待所有的Promise完成
			    Promise.all(promises).then(() => {
			        const totalQuestions = questionIds;
			        const accuracy = ((correctCount / totalQuestions.length) * 100).toFixed(2);
			        const submitTime = new Date().toISOString();
			
			        // 处理报告导航
			        let practiceType = "";
			        if (this.question.type) {
			            const types = {
			                1: "常识判断",
			                2: "数量关系",
			                3: "判断推理",
			                4: "资料分析",
			                5: "言语理解与表达",
							6: "政治理论"
			            };
			            practiceType = types[this.question.type] || "未知类型";
			        }
			        this.navigateToReport(practiceType, endTime, timeTaken, accuracy, totalQuestions, wrongIds);
			    });
			},
			navigateToReport(exerciseType, endTime, timeTaken, accuracy, totalQuestions, wrongIds) {
				const reportData = {
					exerciseType,
					submissionTime: new Date(endTime).toLocaleString(),
					timeTaken,
					accuracy,
					totalQuestions,
					incorrectQuestions: wrongIds
				};

				// 跳转到 report 页面并传递数据
				uni.navigateTo({
					url: `/subPackageA/report?data=${encodeURIComponent(JSON.stringify(reportData))}&dttype=1`
				});
			},
			back() {
				if (this.index == 0) {
					toast('已经是第一题了哦');
					return;
				}
				this.updateUserAnswer(this.question.id, this.userAnswer);
				this.index = this.index - 1;
			},
			next() {
				if (this.isSubmitted) {
					if (this.index < this.questionList.length - 1) {
						this.updateUserAnswer(this.question.id, this.userAnswer);
						this.index = this.index + 1;
					}
					return;
				}

				if (this.index === this.questionList.length - 1) {
					let allAnswered = this.answers.every(answer => answer.userAnswer !== null);
					if (!allAnswered) {
						uni.showModal({
							content: '当前还有题目未完成哦',
							showCancel: true,
							cancelText: '再做会儿',
							confirmText: '坚持交卷',
							success: (res) => {
								if (res.confirm) {
									this.submit();
								}
							}
						});
					} else {
						this.submit();
					}
				} else {
					this.updateUserAnswer(this.question.id, this.userAnswer);
					this.index = this.index + 1;
				}
			},
			updateUserAnswer(questionId, newAnswer) {
				const itemIndex = this.answers.findIndex(item => item.questionId == questionId);
				if (itemIndex !== -1) {
					this.answers[itemIndex].userAnswer = newAnswer;
				}
			},
			touchStart(event) {
				this.startX = event.touches[0].clientX; // 记录触摸开始的X坐标
			},
			touchEnd(event) {
				const endX = event.changedTouches[0].clientX; // 触摸结束的X坐标
				const distance = this.startX - endX; // 计算滑动的距离

				if (distance > 50) {
					// 向左滑动，进入下一题
					this.next();
				} else if (distance < -50) {
					// 向右滑动，返回上一题
					this.back();
				}
			},
		}
	};
</script>

<style lang="scss" scoped>
	.space {
		padding-bottom: 18%;
	}
	
	.content-container {
	    padding-bottom: 3%;
	    overflow: auto;
	}

	.bottom {
		margin-top: 5%;
		width: 100%;
		justify-content: center;
		display: flex;
		align-items: center;

		.hint {
			padding: 20rpx 10rpx;
			font-size: 25rpx;
			color: $u-tips-color;

			.link {
				color: $u-type-primary;
			}
		}
	}

	.rounded-card {
		border-radius: 14px;
		padding: 10px;
		margin-bottom: 10px;
		background-color: #fff;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.explanation-card {
		margin-bottom: 60px;
	}

	.card-content {
		padding: 5px;
	}

	.circle-button {
		margin-top: 5px;
		padding: 10px;
		width: 50px;
		height: 50px;
		border-radius: 50%;
		border: 2px solid #09AFFF;
		background-color: #09AFFF;
		color: white;
		display: flex;
		justify-content: center;
		align-items: center;
		border: none;
		outline: none;
		cursor: pointer;
		font-size: 16px;
		font-family: Arial, sans-serif;
		transition: background-color 0.3s ease;
	}

	.circle-button:hover {
		background-color: #0056b3;
	}
</style>